/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 11, 2012  12:28:02 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.sd.outbound
 * File Name : VwSyncMktCustBookContService.java
 * TODO
 */
package sap.business.sd.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.SdBookContrOutb;
import jpa.entitys.synchro.staging.SdBookContrOutbJoinowner;
import jpa.entitys.synchro.staging.SdContarctUtility;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.SdBookContrOutbJoinownerServices;
import jpa.service.synchro.staging.SdBookContrOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class VwSyncMktCustBookContService extends SynchroOutAbstract {

	private static final Logger log = Logger.getLogger(VwSyncMktCustBookContService.class);
	private SdBookContrOutbServices SdBookContrOutbServ = null;
	private SdBookContrOutbJoinownerServices SdBookContrOutbJoinownerServ = null;
	
	private String sap_table_utility;
	private String sap_table_partner;
	private String sap_table_remark;
	private String sap_table_item_installment;
	
	/**
	 * 
	 */
	public VwSyncMktCustBookContService() {
		
		try {
						
			this.sap_bapi = "ZIN_SD_REALESTATE_PROCESSING";			
			this.sap_table = "HEADER";
			this.sap_table_partner = "PARTNERS";
			this.sap_table_remark = "REMARK";
			this.sap_table_item_installment = "ITEM_INSTALLMENT";
			this.sap_table_utility = "UTILITIES";
			this.sap_table_return = "RETURN";			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}

	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list, String isSync) throws Exception {
		if(!jcoTable.isEmpty())
		{
			System.out.println("Bapi = "+ sap_bapi +", table : "+ sap_table +" is Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			System.out.println("value_list.size : " + value_list.size());			
			System.out.println("table.getNumRows : " + jcoTable.getNumRows());
			
			jcoTable.deleteAllRows();
			SdBookContrOutb model = (SdBookContrOutb)value_list.get(0);
			System.out.println(" -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " InstanceNo = " + model.getInstanceNo() + " DocumentNumber = " + model.getDocumentNumber() + " Installment Seq : " + model.getInstallmentSeq().toString());
			
			jcoTable.appendRow();
			//jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
			
			jcoTable.setValue("INTERFACE_NO", model.getInterfaceNo());
			
			jcoTable.setValue("PROMIS_DOCNO", model.getDocumentNumber());
			jcoTable.setValue("PROMIS_BOOKNO", model.getBookingDocumentNo());
			jcoTable.setValue("PROMIS_CONTRACT", model.getContractDocumentNoMain());
			jcoTable.setValue("PROMIS_SUBCT", model.getContractDocumentNo());
			jcoTable.setValue("PROMIS_ADDRKEY", model.getAddressCode());
			jcoTable.setValue("PROMIS_UNITCODE", model.getUnitNumber());
			jcoTable.setValue("DOC_TYPE", model.getDocumentType());
			jcoTable.setValue("BUSINESS_GRP", model.getBusinessGroup());
			jcoTable.setValue("PROPTYP", model.getPropertyTypeCode());
			jcoTable.setValue("UNITTYP", model.getProductCode());
			jcoTable.setValue("PURCH_DATE", model.getBookingDate());
			jcoTable.setValue("CONTRACT_DATE", model.getContractDate());
			jcoTable.setValue("MARK_FLAG_DATE", model.getSignedOn());
			jcoTable.setValue("PURCH_NO_C", "");
			jcoTable.setValue("PURCH_NO_S", model.getProjectName());
			jcoTable.setValue("DOC_STATUS", model.getDocumentStatus());
			jcoTable.setValue("LIST_PRICE", model.getSaleDocumentAmount());
			jcoTable.setValue("DISCOUNT_CONTRACT", model.getTotalDiscountAmount());
			jcoTable.setValue("TOTAL_AMOUNT", model.getNetDocumentAmount());
			jcoTable.setValue("PRICE_UNIT", model.getNetPriceTransSwq());
			jcoTable.setValue("CONTRACT_CURR", model.getCurrency());
			jcoTable.setValue("TRANS_PRICE", model.getNetUnitSaleAmount());
			jcoTable.setValue("DISCOUNT_TRANSF", model.getTransferDiscount());
			jcoTable.setValue("TRANS_CURR", model.getCurrency());
			jcoTable.setValue("TRANS_DATE", model.getTransferDate());
			jcoTable.setValue("TRANS_FUR_AMT", model.getFurnitureAmount());
			jcoTable.setValue("STATUS_ALT", model.getRequestStatus());
			jcoTable.setValue("UTILITIES_DATE", model.getCsTransferDate());		
			jcoTable.setValue("AREA_CHG_AMT", model.getAdjustAmount());
			
			JCoTable jCoTable1 = Remark(jcoFunction, (SdBookContrOutb)value_list.get(0));
			
			JCoTable jCoTable2 = Partner(jcoFunction, (SdBookContrOutb)value_list.get(0), isSync);
			
			JCoTable jCoTable3 = Installment(jcoFunction, value_list);
			
			JCoTable jCoTable4 = Utility(jcoFunction, ((List<SdContarctUtility>)model.getOthers()));
			
			System.out.println(" Header : " + jcoTable.getNumRows());
			SynchroToSap(jcoFunction, jcoTable, jCoTable1, jCoTable2, jCoTable3, value_list);
		}		
	}

	
	private JCoTable Utility(JCoFunction jcoFunction, List<SdContarctUtility> value_list) throws Exception {
		try{
			JCoTable jcoTable = jco_conn.getTables(this.sap_table_utility);
			if(!CommonService.IsNull(value_list)){			
				
				System.out.println("value_list.size : " + value_list.size());
				System.out.println("table.getNumRows : " + jcoTable.getNumRows());
				
				for (SdContarctUtility vlaue : value_list)
		        {
					System.out.println(" -- PROMIS_TXN_ID = " +  vlaue.getPromisStagingId() + " InstanceNo = " + vlaue.getInstanceNo() + "Documentno = " + vlaue.getDocumentno());
					
					jcoTable.appendRow();
					jcoTable.setValue("PROMIS_TXN_ID", vlaue.getPromisStagingId());
					jcoTable.setValue("ITEM_CATEG", vlaue.getItemCateg());
					jcoTable.setValue("PRICE_AMOUNT", vlaue.getPriceAmount());
					jcoTable.setValue("CURRENCY", vlaue.getCurrency());
					jcoTable.setValue("TAX_CODE", vlaue.getTaxCode());
					jcoTable.setValue("TAX_BASE_AMOUNT", vlaue.getTaxBaseAmount());
					jcoTable.setValue("TAX_AMOUNT", vlaue.getTaxAmount());
					jcoTable.setValue("PRICE_UNIT", vlaue.getPriceAmount());
					jcoTable.setValue("DUE_DATE", vlaue.getDueDate());
					jcoTable.setValue("PERIOD", vlaue.getPeriod());
					jcoTable.setValue("START_PERIOD", vlaue.getStartPeriod());
					jcoTable.setValue("END_PERIOD", vlaue.getEndPeriod());
					jcoTable.setValue("SEQ_CODE", vlaue.getSeqNo());
					jcoTable.setValue("PERIOD_UNIT", vlaue.getTypeOfPeriod());
		        }
			}
			
			return jcoTable;
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, JCoTable jcoTable1, JCoTable jcoTable2, JCoTable jcoTable3, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		jcoFunction.execute(jco_conn.getJCoConnection());
		System.out.println("Sending to SAP ");
	}
	
	private JCoTable Partner(JCoFunction jcoFunction, SdBookContrOutb value, String isSync) throws Exception {
		
		//Get SAP Staging table Partner
		JCoTable jcoTable = jco_conn.getTables(this.sap_table_partner);
		
		//Primary Customer
		jcoTable.appendRow();
		jcoTable.setValue("PARTN_ROLE", "AG");
		jcoTable.setValue("PARTN_NUMB", value.getCustomerCode()); 
		jcoTable.setValue("PARTN_COND", value.getCustomerName());
		System.out.println("PARTN_ROLE : "+ jcoTable.getString("PARTN_ROLE") +" // PARTN_NUMB : " + jcoTable.getString("PARTN_NUMB") +  " // PARTN_COND ; " + jcoTable.getString("PARTN_COND"));
		
		//joint Costomer
		List<SdBookContrOutbJoinowner> value_list = SdBookContrOutbJoinownerServ.findByDocumentNo(value.getCompany() , value.getProject(), value.getDocumentNumber(), value.getInstanceNo(), isSync);		
		if(!CommonService.IsNull(value_list)){			
			if(!CommonService.IsNull(value_list)){
				System.out.println("value_list.size : " + value_list.size());
				System.out.println("table.getNumRows : " + jcoTable.getNumRows());
				
				for (SdBookContrOutbJoinowner model : value_list) 
		        {
					System.out.println("-- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " InstanceNo = " + model.getInstanceNo() + "OwnerCode = " + model.getOwnerCode());
					
					jcoTable.appendRow();
					jcoTable.setValue("PARTN_ROLE", "P" + model.getOwnerRoleSeq());
					jcoTable.setValue("PARTN_NUMB", model.getOwnerCode());
					jcoTable.setValue("PARTN_COND", model.getAndorDesc());
					
					System.out.println("PARTN_ROLE : "+ jcoTable.getString("PARTN_ROLE") +" // PARTN_NUMB : " + jcoTable.getString("PARTN_NUMB") +  " // PARTN_COND ; " + jcoTable.getString("PARTN_COND"));
		        }
			}
		}
		
		System.out.println("Partner row count : "  + jcoTable.getNumRows());
		
		return jcoTable;
	}
	
	private JCoTable Remark(JCoFunction jcoFunction, SdBookContrOutb value) throws Exception {
		
		JCoTable jcoTable1 = jco_conn.getTables(this.sap_table_remark);
		jcoTable1.appendRow();
		jcoTable1.setValue("REMARK_DESC", value.getRemarks());
		
		return jcoTable1;
		
	}
	
	private JCoTable Installment(JCoFunction jcoFunction, List<?> value_list) throws Exception {
		
		JCoTable jcoTable = jco_conn.getTables(this.sap_table_item_installment);		
		
		if(!CommonService.IsNull(value_list)){
			
			if(!jcoTable.isEmpty())
			{
				System.out.println("Bapi = "+ sap_bapi +", table : "+ sap_table_item_installment +" is Empty ");
				return null;
			}	
			
			if(!CommonService.IsNull(value_list)){
				System.out.println("value_list.size : " + value_list.size());			
				System.out.println("table.getNumRows : " + jcoTable.getNumRows());
				
				jcoTable.deleteAllRows();
				for (Object obj : value_list) 
		        {
					SdBookContrOutb model = (SdBookContrOutb)obj;
					System.out.println(" -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + " InstanceNo = " + model.getInstanceNo() + " INSTALLMENT_SEQ = " + model.getInstallmentSeq().toString());
					
					jcoTable.appendRow();
					jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
					jcoTable.setValue("ITM_NUMBER", model.getInstallmentSeq().toString());
					jcoTable.setValue("ITM_CODE", model.getPaymentInstallment());
					jcoTable.setValue("CUST_MAT_DESC", model.getPaymentTypeDesc());
					jcoTable.setValue("ITEM_CATEG", model.getIncomeFlag());
					jcoTable.setValue("PLANT_CODE", model.getSapPlantCode());
					jcoTable.setValue("PRICE_AMOUNT", model.getInstallmentDueAmount());
					jcoTable.setValue("CURRENCY", model.getCurrency());
					jcoTable.setValue("TAX_CODE", model.getVatCode());
					jcoTable.setValue("TAX_BASE_AMOUNT", model.getVatBase());
					jcoTable.setValue("TAX_AMOUNT", model.getVatAmount());
					jcoTable.setValue("WHT_CODE", model.getWhtSubcode());
					jcoTable.setValue("WHT_BASE", model.getWhtBase());
					jcoTable.setValue("WHT_AMOUNT", model.getWhtAmount());
					jcoTable.setValue("DUE_DATE", model.getInstallmentDueDate());
					jcoTable.setValue("PAYMENT_METHOD", "");
					jcoTable.setValue("SUPALAI_ACCOUNT", model.getChequePayeeAc());
					jcoTable.setValue("PRE_PRINT", model.getDocumentRef());
					
					//Add file 2012-06-14 for UAT
					jcoTable.setValue("PAID_AMOUNT", model.getInstallmentAmountPaid());
					jcoTable.setValue("PAID_DATE", model.getInstallmentPaidDate());
					
		        }
			}		
		}
		
		return jcoTable;
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		List<SdBookContrOutb> lst = new ArrayList<SdBookContrOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			System.out.println("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				SdBookContrOutb model = SdBookContrOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				System.out.println(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			SdBookContrOutbServ.Updated(lst);
		}else
			System.out.println(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<SdBookContrOutb> value_list, Exception error) throws Exception{
		System.out.println("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<SdBookContrOutb> newlst = new ArrayList<SdBookContrOutb>();
				for(SdBookContrOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new SdBookContrOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			System.out.println("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	private void groupBy() throws Exception {
		try{
			
			
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	private List<SdBookContrOutb> Search() throws Exception {
		List<SdBookContrOutb> lst = new ArrayList<SdBookContrOutb>();
		List<SdBookContrOutb> lst_temp = new ArrayList<SdBookContrOutb>();
		try{
			
			String company = "SP";
			String project = "SPLCITY-SRI";
			//String documentNo = "";
			String promisDocStatus = "A";
			String issync = "N";
			
			String promisDocType = "BS";  //CS 
			//lst = SdBookContrOutbServ.findByDocument(company, project, documentType, documentNo, status, issync);
			lst = SdBookContrOutbServ.findByDocumentType(company, project, promisDocType, promisDocStatus, issync);
			
			System.out.println(lst.size());
			
//			promisDocType = "CS"; //BS
//			lst_temp = SdBookContrOutbServ.findByDocumentType(company, project, promisDocType, promisDocStatus, issync);
//			System.out.println(lst.size());
//			
//			if(!CommonService.IsNull(lst_temp)){
//				for(SdBookContrOutb value : lst_temp){
//					lst.add(value);
//				}
//			}
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
		return lst;
	}
	
	/**
	 * 
	 * @param value_list
	 * @param issync
	 * @throws Exception
	 */
	public void SendingToSAP(List<SdBookContrOutb> value_list, String issync) throws Exception {
		System.out.println("Start SendingToSAP. ");
		try{
			if(!CommonService.IsNull(value_list))
			{
				this.jco_conn  = new Connection();
				
				SdBookContrOutbServ = new SdBookContrOutbServices(this.emSynchro);
				SdBookContrOutbJoinownerServ = new SdBookContrOutbJoinownerServices(this.emSynchro);
	
				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table Header
				JCoTable jcoTable = jco_conn.getTables(sap_table);			
			
				//Send to SAP
				SynchroToSap(jcoFunction, jcoTable, value_list, issync);
							
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
				
			}else 
				log.warn(" SendingToSAP is null ");
			
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);	

			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	/**
	 * 
	 * @param company
	 * @param project
	 * @param promisDocType
	 * @param documentNo
	 * @param status
	 * @param instanceNo
	 * @param issync
	 * @throws Exception
	 */
	public void SendingToSAP(String company, String project, String promisDocType, String documentNo, String status, String instanceNo, String issync) throws Exception {
		System.out.println("Start SendingToSAP. ");
		List<SdBookContrOutb> value_list = null;
		try{
			
			this.jco_conn  = new Connection();
			
			SdBookContrOutbServ = new SdBookContrOutbServices(this.emSynchro);
			SdBookContrOutbJoinownerServ = new SdBookContrOutbJoinownerServices(this.emSynchro);

			//Get SAP BAPI function
			JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
			
			//Get SAP Staging table Header
			JCoTable jcoTable = jco_conn.getTables(sap_table);
			value_list =  SdBookContrOutbServ.findByDocument1(company, project, promisDocType, documentNo, status, instanceNo, issync);
					
			if(!CommonService.IsNull(value_list))
			{
				SynchroToSap(jcoFunction, jcoTable, value_list, issync);
							
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
			}else 
				log.warn(" findByDocument is null ");
			
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);	
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}		
	}
	
	@Deprecated
	private void Start() throws Exception
	{		
		this.jco_conn  = new Connection();
		
		SdBookContrOutbServ = new SdBookContrOutbServices(this.emSynchro);
		SdBookContrOutbJoinownerServ = new SdBookContrOutbJoinownerServices(this.emSynchro);

		//Get SAP BAPI function
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table Header
		JCoTable jcoTable = jco_conn.getTables(sap_table);		
		List<SdBookContrOutb> value_list =  Search();	//SdBookContrOutbServ.findAllIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, value_list);
				
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
		
	}
	
	
//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub		
//		try{
//			
//			VwSyncMktCustBookContService VwSyncMktCustBookContServ	= new VwSyncMktCustBookContService();
//			
//			VwSyncMktCustBookContServ.Start();
//			
//		}catch(Exception ex)
//		{
//			log.error(ex);
//		}
//	}

}
